<template>
  <div class="currency-container">
    <div class="page-header">
      <h2 class="page-title">币种监控列表</h2>
    </div>
    
    <div class="content-wrapper">
      <div class="search-bar">
        <div class="search-inputs">
          <el-input
            v-model="searchQuery"
            placeholder="请输入币种名称搜索"
            class="search-input"
            clearable
            @clear="fetchSymbols"
          >
            <template #append>
              <el-button @click="fetchSymbols">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          <el-select v-model="statusFilter" placeholder="监控状态" clearable @change="fetchSymbols" class="status-select">
            <el-option label="监控中" value="1" />
            <el-option label="停止监控" value="0" />
          </el-select>
        </div>
        <div class="operation-buttons">
          <el-button type="success" @click="refreshMonitoredSymbols">
            <el-icon><Refresh /></el-icon> 刷新监控币种
          </el-button>
          <el-button 
            type="warning" 
            :disabled="selectedRows.length === 0"
            @click="batchUpdateStatus(true)"
          >
            <el-icon><VideoPlay /></el-icon> 批量开始监控
          </el-button>
          <el-button 
            type="danger" 
            :disabled="selectedRows.length === 0"
            @click="batchUpdateStatus(false)"
          >
            <el-icon><VideoPause /></el-icon> 批量停止监控
          </el-button>
        </div>
      </div>

      <div class="table-container">
        <el-table 
          :data="symbolsList" 
          style="width: 100%" 
          border 
          v-loading="loading"
          @selection-change="handleSelectionChange"
          height="calc(100vh - 240px)"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" min-width="180" />
          <el-table-column prop="symbolName" label="币种名称" min-width="150" />
          <el-table-column prop="status" label="监控状态" min-width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
                {{ scope.row.status === '1' ? '监控中' : '停止监控' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="changeRate" label="涨跌幅" min-width="120">
            <template #default="scope">
              <span :class="(scope.row.changeRate || 0) >= 0 ? 'rate-up' : 'rate-down'">
                {{ (scope.row.changeRate || 0) >= 0 ? '+' : '' }}{{ scope.row.changeRate || '0.00' }}%
              </span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="150">
            <template #default="scope">
              <el-button
                :type="scope.row.status === '1' ? 'danger' : 'success'"
                size="small"
                @click="handleToggleStatus(scope.row)"
                text
              >
                {{ scope.row.status === '1' ? '停止监控' : '开始监控' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Search, Plus, Refresh, VideoPlay, VideoPause } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const loading = ref(false)
const symbolsList = ref([])
const selectedRows = ref([])

// 从API获取币种数据
const fetchSymbols = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://127.0.0.1:1234/symbols/page', {
      params: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        symbolName: searchQuery.value || undefined,
        status: statusFilter.value || undefined
      }
    })
    
    if (response.data && response.data.records) {
      symbolsList.value = response.data.records.map(item => ({
        ...item,
        changeRate: (Math.random() * 10 - 5).toFixed(2) // 模拟涨跌幅数据，实际应从API获取
      }))
      total.value = response.data.total || 0
    } else {
      symbolsList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取币种数据失败:', error)
    ElMessage.error('获取币种数据失败，请稍后重试')
    symbolsList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 刷新监控币种
const refreshMonitoredSymbols = async () => {
  try {
    loading.value = true
    await axios.post('http://127.0.0.1:1234/symbols/refresh')
    ElMessage.success('刷新监控币种成功')
    // 刷新后重新加载数据
    await fetchSymbols()
  } catch (error) {
    console.error('刷新监控币种失败:', error)
    ElMessage.error('刷新监控币种失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
}

// 批量更新状态
const batchUpdateStatus = (monitored) => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要操作的币种');
    return;
  }
  
  const message = monitored ? '开始监控' : '停止监控';
  // 保持ID为字符串类型，避免大整数精度丢失
  const ids = selectedRows.value.map(row => row.id);
  // 正确的状态值：0是停止监控，1是开始监控
  const status = monitored ? 1 : 0;
  
  ElMessageBox.confirm(
    `确定要批量${message}选中的 ${selectedRows.value.length} 个币种吗？`,
    '批量操作提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await axios.post('http://127.0.0.1:1234/symbols/batch-update', {
        ids: ids,
        status: status
      });
      ElMessage.success(`批量${message}成功`);
      // 重新加载数据
      fetchSymbols();
    } catch (error) {
      console.error(`批量${message}失败:`, error);
      ElMessage.error(`批量${message}失败，请稍后重试`);
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

// 处理状态切换
const handleToggleStatus = (row) => {
  const newStatus = row.status === '1' ? false : true
  const message = newStatus ? '开始监控' : '停止监控'
  
  ElMessageBox.confirm(
    `确定要${message}币种 ${row.symbolName} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await axios.put(`http://127.0.0.1:1234/symbols/currencies/${row.symbolName}/monitor`, null, {
        params: {
          monitored: newStatus
        }
      })
      ElMessage.success(`${message}成功`)
      // 重新加载数据
      fetchSymbols()
    } catch (error) {
      console.error(`${message}失败:`, error)
      ElMessage.error(`${message}失败，请稍后重试`)
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchSymbols()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchSymbols()
}

// 初始化时从API获取数据
onMounted(() => {
  fetchSymbols()
})
</script>

<style scoped>
.currency-container {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.page-header {
  background-color: #fff;
  padding: 16px 24px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.content-wrapper {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 60px);
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.search-inputs {
  display: flex;
  gap: 15px;
}

.search-input {
  width: 300px;
}

.status-select {
  width: 150px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.table-container {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.pagination {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.rate-up {
  color: #67c23a;
  font-weight: bold;
}

.rate-down {
  color: #f56c6c;
  font-weight: bold;
}
</style>